let BASE_CODE = `${process.env.VUE_APP_URL}/imgcode`
export default {
  computed: {
    btnDisabled() {
      // 禁用按钮
      return this.down_time > 0
    },
    btnCodeText() {
      if (this.sending) {
        return '发送中'
      } else {
        return this.down_time > 0 ? this.down_time + '秒' : '获取验证码'
      }
    },
  },
  data() {
    return {
      down_time: 0,
      sending: false,
    }
  },
  methods: {
    // 检验验证码
    async checkCaptcha(code) {
      let res = await this.$api.common.system('checkVerifyCode', {
        code,
      })
      if (res.code === 200) {
        return true
      } else {
        return false
      }
    },
    // 随机字符串
    randomString(len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    validMobile(mobile) {
      const reg = /^1[0-9]{10}$/
      return reg.test(mobile)
    },
    async imgCode() {
      this.img_url = `${BASE_CODE}?t=${this.randomStr(10)}`
    },
    // 生成随机验证码
    getRandomImgCode() {
      this.img_url = `${BASE_CODE}?t=${this.randomStr(10)}`
    },
    // 发送验证码
    async sendCaptcha(phone, scene, imgcode) {
      if (this.sending || this.down_time > 0) {
        return
      }
      if (scene) {
        this.scene = scene
      }
      // 验证码类型：register注册验证码，login登录，bind绑定 ，destory_account注销 verify_mobile验证，change_bind修改手机
      if (!this.scene) {
        this.showMsg('请先配置验证码类型')
        return
      }
      if (!(phone || this.mobile)) {
        this.showMsg('请输入手机号码')
        return
      }
      if (!this.validMobile(phone || this.mobile)) {
        this.showMsg('请输入正确的手机号码')
        return
      }
      if (!imgcode) {
        this.showMsg('请输入图片验证码')
        return
      }
      this.sending = true

      let json = {
        mobile: phone || this.mobile,
        scene: scene || this.scene,
        imgcode,
        t: this.img_url.split('t=')[1],
      }
      let res = await this.$api.common.user('sednMobileCode', {
        ...json,
      })
      if (res.code === 200) {
        this.sending = false
        this.down_time = 60
        let clearId = setInterval(() => {
          if (this.down_time === 0) {
            clearInterval(clearId)
          }
          if (this.down_time > 0) {
            this.down_time--
          }
        }, 1000)
      } else {
        this.sending = false
      }
    },
  },
}
